import { ElMessage as message } from 'element-plus'
import { session } from '@/utils/storage'
import socket from '@/types/api/socket'
const socket: socket = {
  websocket: null,
  connectURL: 'ws://localhost:8000',
  // 开启标识
  socket_open: false,
  // 心跳timer
  hearbeat_timer: null,
  // 心跳发送频率
  hearbeat_interval: 2 * 1000,
  // 是否自动重连
  is_reonnect: true,
  // 重连次数
  reconnect_count: 3,
  // 已发起重连次数
  reconnect_current: 1,
  // 重连timer
  reconnect_timer: null,
  // 重连频率
  reconnect_interval: 5 * 1000,
  init: (receiveMessage: Function | null) => {
    if (!('WebSocket' in window)) {
      message.warning('浏览器不支持WebSocket')
      return null
    }
    socket.websocket = new WebSocket(socket.connectURL)
    socket.websocket.onmessage = (e: any) => {
      if (receiveMessage) {
        receiveMessage(e)
      }
    }
    socket.websocket.onclose = (e: any) => {
      socket.socket_open = false
      // 需要重新连接
      if (socket.is_reonnect) {
        socket.reconnect_timer = setTimeout(() => {
          // 超过重连次数
          if (socket.reconnect_current > socket.reconnect_count) {
            clearTimeout(socket.reconnect_timer)
            socket.is_reonnect = false
            return
          }
          // 记录重连次数
          socket.reconnect_current++
          socket.reconnect()
        }, socket.reconnect_interval)
      }
    }
    // 连接成功
    socket.websocket.onopen = function () {
      socket.socket_open = true
      socket.is_reonnect = true
      // 开启心跳
      socket.heartbeat()
    }
    // 连接发生错误
    socket.websocket.onerror = function () { }
  },
  heartbeat: () => {
    socket.hearbeat_timer && clearInterval(socket.hearbeat_timer)

    socket.hearbeat_timer = setInterval(() => {
      let data = {
        token: session.get('token')
      }
      socket.send(data)
    }, socket.hearbeat_interval)
  },
  send: (data, callback = null) => {
    // 开启状态直接发送
    if (socket.websocket.readyState === socket.websocket.OPEN) {
      socket.websocket.send(JSON.stringify(data))
      callback && callback()
    } else {
      clearInterval(socket.hearbeat_timer)
      message({
        type: 'warning',
        message: 'socket链接已断开',
        duration: 1000,
      })
    }
  },
  close: () => {
    socket.is_reonnect = false
    socket.websocket.close()
  },
  /**
   * 重新连接
   */
  reconnect: () => {
    if (socket.websocket && !socket.is_reonnect) {
      socket.close()
    }
    socket.init(null)
  },
}
export default socket;